import os
import logging
from logging.handlers import RotatingFileHandler


BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

#The background is set with 40 plus the number of the color, and the foreground with 30

#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"

def formatter_message(message, use_color = True):
    if use_color:
        message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
    else:
        message = message.replace("$RESET", "").replace("$BOLD", "")
    return message

COLORS = {
    'WARNING': YELLOW,
    'INFO': WHITE,
    'DEBUG': BLUE,
    'CRITICAL': YELLOW,
    'ERROR': RED
}


class ColoredFormatter(logging.Formatter):
    def __init__(self, msg, use_color=True):
        logging.Formatter.__init__(self, msg)
        self.use_color = use_color

    def format(self, record):
        levelname = record.levelname
        if self.use_color and levelname in COLORS:
            levelname_color = COLOR_SEQ % (
                30 + COLORS[levelname]) + levelname + RESET_SEQ
            record.levelname = levelname_color
        return logging.Formatter.format(self, record)



# Custom logger class with multiple destinations

class LoggerLog(object):
    
    def __init__(self, name=__name__):
        """
        实例化LoggerFactory类时的构造函数
        :param name:
        """
        # 实例化logging
        self.logger = logging.getLogger(name)
        # 输出的日志格式

        FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s]  %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
        COLOR_FORMAT = formatter_message(FORMAT, True)
        self.formatter = formatter = logging.Formatter(COLOR_FORMAT)

        # self.formatter = formatter = logging.Formatter(
        #     '%(asctime)s %(name)s %(levelname)s %(message)s')

    def create_logger(self):
        """
        构造一个日志对象
        :return:
        """

        # 设置日志输出的文件
        os.makedirs('logs', exist_ok=True)
        # handle = logging.FileHandler('./logs/scripts.log')
        handle = logging.handlers.RotatingFileHandler(
            './logs/scripts.log', maxBytes=1024*1024, backupCount=3)

        # 输出到日志文件的日志级别
        handle.setLevel(logging.INFO)
        handle.setFormatter(self.formatter)
        self.logger.addHandler(handle)
       
        # 输出到控制台的显示信息
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(self.formatter)
        self.logger.addHandler(console)


if __name__ == '__main__':
    logger = LoggerLog("log").get_log
    #  logger .create_logger()
    logger .logger.info('这是测试INFO输出')